// 状态管理，替代uni-id-pages的store
import authManager from './auth.js'
    console.log(authManager,'authManager==============?>');
// 用户信息状态
export const store = {
	userInfo: authManager.getUserInfo(),
	hasLogin: authManager.isLoggedIn()
}

// 状态变更方法
export const mutations = {
	// 登录成功
	loginSuccess(result) {
		if (result && result.userInfo) {
			authManager.setUserInfo(result.userInfo)
		}
		if (result && result.token) {
			authManager.setToken(result.token)
		}
		
		// 更新store状态
		store.userInfo = authManager.getUserInfo()
		store.hasLogin = authManager.isLoggedIn()
		
		// 跳转到首页或返回上一页
		const pages = getCurrentPages()
		if (pages.length > 1) {
			uni.navigateBack()
		} else {
			uni.reLaunch({
				url: '/pages/index/index'
			})
		}
	},
	
	// 退出登录
	logout() {
		authManager.logout()
		store.userInfo = {}
		store.hasLogin = false
	},
	
	// 更新用户信息
	async updateUserInfo(data = false) {
		if (data) {
			try {
				const result = await authManager.updateUserInfo(data)
				store.userInfo = authManager.getUserInfo()
				return result
			} catch (error) {
				throw error
			}
		} else {
			// 从服务器获取最新用户信息
			try {
				const userInfo = await authManager.getCurrentUserInfo()
				store.userInfo = userInfo
				return userInfo
			} catch (error) {
				// 获取失败时清除本地信息
				this.logout()
				throw error
			}
		}
	},
	
	// 设置用户信息
	setUserInfo(userInfo, options = {}) {
		if (options.cover) {
			// 完全覆盖
			store.userInfo = userInfo
		} else {
			// 合并更新
			store.userInfo = {
				...store.userInfo,
				...userInfo
			}
		}
		authManager.setUserInfo(store.userInfo)
		store.hasLogin = authManager.isLoggedIn()
	}
}

// 兼容原有的调用方式
export default {
	store,
	mutations
} 